﻿using System;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using SPEditor.Core;

namespace SPEditor.Layouts
{
    public partial class SPEditor : LayoutsPageBase
    {
        private SPListItem _item;

        protected void Page_Load(object sender, EventArgs e)
        {
            GetItem();
            LoadEditorMetaData();
            LoadEditorContent();
            SetEditorMode();
        }

        protected void BtnSaveClick(object sender, EventArgs e)
        {
            string fileContents = HfFileContents.Value;
            SPFile file = _item.File;
            byte[] byteArray = Encoding.UTF8.GetBytes(fileContents);
            file.ParentFolder.Files.Add(file.Url, byteArray, true);
            SetStatus(Constants.StatusBarMsgSaved, Constants.StatusBarGood);
            LoadEditorContent();
            UpdateTimeStamp();
        }

        protected void BtnCancelClick(object sender, EventArgs e)
        {
            SPUtility.Redirect(SPContext.Current.Site.RootWeb.Url, SPRedirectFlags.UseSource, HttpContext.Current);
        }

        private void SetStatus(string msg, string type)
        {
            PnlStatusBar.CssClass = string.Format("{0} {1}", Constants.StatusBarBaseCss, type);
            LblStatusMessage.Text = msg;
        }

        private void GetItem()
        {
            string siteUrl = Page.Request.QueryString[Constants.QS_SiteUrl];
            string itemId = Page.Request.QueryString[Constants.QS_ItemId];
            string listId = Page.Request.QueryString[Constants.QS_ListId];

            if (!string.IsNullOrEmpty(siteUrl) && !string.IsNullOrEmpty(itemId) && !string.IsNullOrEmpty(listId))
            {
                using (var site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists.GetList(new Guid(listId), false);
                        _item = list.GetItemById(Convert.ToInt32(itemId));
                    }
                }
            }
        }

        private void UpdateTimeStamp()
        {
            LblModifed.Text =
                Convert.ToDateTime(_item[SPBuiltInFieldId.Last_x0020_Modified]).ToString("dddd, dd MMMM yyyy HH:mm:ss");
        }

        private void LoadEditorMetaData()
        {
            string author = Convert.ToString(_item[SPBuiltInFieldId.Author]);
            LblAuthor.Text = author.Substring(author.IndexOf('#') + 1);
            LblFileName.Text = Convert.ToString(_item[SPBuiltInFieldId.FileLeafRef]);
            LblTitle.Text = Convert.ToString(_item[SPBuiltInFieldId.Title]);
            LblModStat.Text = Convert.ToString(_item[SPBuiltInFieldId._ModerationStatus]);
            LblCheckedOutStatus.Text = Convert.ToString(_item.File.CheckOutType);
            HfFileMode.Value = Convert.ToString(_item[SPBuiltInFieldId.File_x0020_Type]);
            double fileSize = Convert.ToDouble(_item[SPBuiltInFieldId.File_x0020_Size]);
            fileSize = fileSize / 1000;
            fileSize = Math.Ceiling(fileSize);
            LblFileSize.Text = fileSize.ToString() + "KB";
            UpdateTimeStamp();
        }

        private bool MatchFileType(string param, string[] fileTypes)
        {
            return fileTypes.Any(fileType => string.Compare(param, fileType, StringComparison.OrdinalIgnoreCase) == 0);
        }

        private void LoadEditorContent()
        {
            string fileContents = _item.Web.GetFileAsString(_item.Url);
            string fileType = Convert.ToString(_item[SPBuiltInFieldId.File_x0020_Type]);

            if (MatchFileType(fileType, Constants.HtmlEncodeFileTypes))
            {
                fileContents = HttpUtility.HtmlEncode(fileContents);
            }
            LitFileContents.Text = string.Format(Constants.FileContentsWrapper, fileContents);
        }

        private void SetEditorMode()
        {
            if (_item.File.CheckOutType == SPFile.SPCheckOutType.None && _item.File.RequiresCheckout)
            {
                LblCheckedOutStatus.Text = Constants.CheckOutStatusMessageNone;
                SetStatus(Constants.StatusBarMsgFileNotCheckedOut, Constants.StatusBarWarn);
                BtnSave.Enabled = false;
                HfReadOnly.Value = Convert.ToString(true);
            }
            else if (_item.File.CheckOutType == SPFile.SPCheckOutType.Online)
            {
                if (_item.File.CheckedOutByUser.LoginName != SPContext.Current.Web.CurrentUser.LoginName)
                {
                    var checkedOutByUser = _item.File.CheckedOutByUser.LoginName;
                    LblCheckedOutStatus.Text = string.Format(Constants.CheckOutStatusMessageOnlineUneditable,
                                                             checkedOutByUser);
                    SetStatus(string.Format(Constants.StatusBarMsgFileCheckOutByUser, checkedOutByUser),
                              Constants.StatusBarWarn);
                    BtnSave.Enabled = false;
                    HfReadOnly.Value = Convert.ToString(true);
                }
                else
                {
                    LblCheckedOutStatus.Text = Constants.CheckOutStatustMessageOnlineEditable;
                    SetStatus(Constants.StatusBarMsgReady, Constants.StatusBarInfo);
                }
            }
            else
            {
                LblCheckedOutStatus.Text = Constants.CheckOutStatusMessageNotRequired;
                SetStatus(Constants.StatusBarMsgReady, Constants.StatusBarInfo);
            }
        }
    }
}